import cv2
import copy
import numpy as np
img = cv2.imread("image/mili.png")
cv2.imshow("img0",img)
img_gray = cv2.cvtColor(img,cv2.COLOR_RGBA2GRAY)
rows,cols = img_gray.shape[:2]
img_up = img_gray[0:int(rows*0.73),0:cols]
img_down = img_gray[int(rows*0.73):rows,0:cols]
# up上部分二值化
kernel = np.ones((5,5),np.uint8)
erosion = cv2.morphologyEx(img_up,cv2.MORPH_OPEN,kernel)
thr_up, bw_up = cv2.threshold(erosion, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow("bw_up",bw_up)
# down下部分二值化
erosion = cv2.morphologyEx(img_down,cv2.MORPH_OPEN,kernel)
thr_down, bw_down = cv2.threshold(erosion, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow("bw_down",bw_down)
bw = np.vstack((bw_up, bw_down))
cv2.imshow("img_combined",bw)

seg = copy.deepcopy(bw)
cnts,hier = cv2.findContours(seg,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
count = 0
# 循环遍历轮廓
for i in range(len(cnts),0,-1):
    #获取当前轮廓
    c = cnts[i - 1]
    # 计算轮廓面积
    area = cv2.contourArea(c)
    # 过滤小轮廓
    if area < 10 :
        continue
    # 计数并打印
    count += 1
    # 获取轮廓的边界矩形，获取当前轮廓的最小外接矩形的左上角坐标(x,y)以及宽度w和高度h
    x,y,w,h = cv2.boundingRect(c)
    # 绘制矩形，在图像img上绘制一个红色的矩形框，框柱当前blob的外接矩形
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),1)
    # 添加文本标注，在轮廓的左上角位置添加文本标注，显示当前的blob计数，文本颜色是绿色
    cv2.putText(img,str(count),(x,y),cv2.FONT_HERSHEY_PLAIN,0.5,(0,255,0))
print("count = ",count)
cv2.imshow("0：",img)
cv2.waitKey()
cv2.destroyAllWindows()